package com.fwj.authorization.security.verifyCode;

import com.alibaba.druid.support.json.JSONUtils;
import lombok.Getter;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * 获取用户登录时携带的额外信息
 *
 * @author fwj
 * @date 2025-03-18
 */
@Getter
public class CustomWebAuthenticationDetails extends WebAuthenticationDetails {

    private static final long serialVersionUID = 1L;

    private final String verifyCode;
    private final String username;
    private final String password;
    private final String tenantId;

    public CustomWebAuthenticationDetails(HttpServletRequest request) {
        super(request);
        /* verifyCode为页面中验证码的name */
        String requestBody = getRequestBody(request);
        Object parse = JSONUtils.parse(requestBody);
        if (parse != null) {
            verifyCode = ((String) ((java.util.Map<?, ?>) parse).get("verifyCode"));
            username = ((String) ((java.util.Map<?, ?>) parse).get("username"));
            password = ((String) ((java.util.Map<?, ?>) parse).get("password"));
            tenantId = ((String) ((java.util.Map<?, ?>) parse).get("tenantId"));
        } else {
            verifyCode = request.getParameter("verifyCode");
            username = request.getParameter("username");
            password = request.getParameter("password");
            tenantId = request.getParameter("tenantId");
        }
    }

    @Override
    public String toString() {
        return super.toString() + "; VerifyCode: " + this.getVerifyCode();
    }

    public String getRequestBody(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } catch (IOException e) {
            throw new RuntimeException("读取请求体失败", e);
        }
    }
}